var apiUrl = "http://112.91.146.165:13805/";

// 获取token
var tokenFlag = false;
var tokenVal;
var apiData;
var initMapData = [];
var petitionListData,
  industryPointListData,
  livePointListData,
  functionAreaData,
  builidPointListData,
  trafficPointListData,
  memsPointListData,
  monitorSourceListData,
  functionPointListData,
  sensitiveInfoData;
$.ajax({
  type: "POST",
  url: apiUrl + "comleader/dataOutput/getSubMapInfo",
  dataType: "application/json",
  headers: {
    "Content-Type": "application/json",
    accessToken: "comleader@123",
  },
  data: JSON.stringify({
    // type: "",
    // page: 1,
    // pageSize: 10,
  }),
  complete: (res) => {
    console.log(res);
    if (res.readyState == 4) {
      var resData = JSON.parse(res.responseText).data;
      var apiDataTypes = Object.keys(resData);

      for (let type of apiDataTypes) {
        initMapData.push(resData[type]);
      }
      console.log(initMapData);
      petitionListData = initMapData[0];
      industryPointListData = initMapData[1];
      livePointListData = initMapData[2];
      functionAreaData = initMapData[3];
      builidPointListData = initMapData[4];
      trafficPointListData = initMapData[5];
      memsPointListData = initMapData[6];
      monitorSourceListData = initMapData[7];
      functionPointListData = initMapData[8];
      sensitiveInfoData = initMapData[9];
    }

    // if (res.status === 200) {
    //   tokenVal = JSON.parse(res.responseText).token;
    //   tokenFlag = true;
    //   getResultList(tokenVal);
    //   console.log(JSON.parse(res.responseText).token);
    // }
  },
});
// 按类别加载点位
function loadListData(listData) {
  console.log(eval(listData));

  if (graphicLayer != null) {
    console.log("清空graphicLayer");
    map.removeLayer(graphicLayer);
    graphicLayer = null;
    graphicLayer = new mars3d.layer.GraphicLayer();
    map.addLayer(graphicLayer);
    graphicLayer.on(mars3d.EventType.click, function (event) {
      console.log(event.graphic.name);
    });
  }
  if (listData == "monitorSourceListData") {
    // 监测源数据经度的单词拼写错误
    for (let item of eval(listData)) {
      if (!!item.longtitude && !!item.latitude) {
        // console.log(item);
        initPOI(
          [item.longtitude, item.latitude],
          item.sourceCode,
          item.sourceName
        );
      }
    }
  } else if (listData == "petitionListData") {
    // 投诉点坐标返回格式和其他不同
    console.log(333);
    for (let item of eval(listData)) {
      console.log(item.petitionObjLatlog);
      initPOI(
        [
          parseFloat(item.petitionObjLatlog.split(",")[0]),
          parseFloat(item.petitionObjLatlog.split(",")[1]),
        ],
        item.petitionObjStreet,
        item.petitionTitle
      );
    }
  } else {
    for (let item of eval(listData)) {
      if (!!item.longitude && !!item.latitude) {
        // console.log(item);
        initPOI(
          [item.longitude, item.latitude],
          item.pointCode,
          item.pointName
        );
      }
    }
  }
}
// 画点位
function initPOI(pos, poiName, poiText) {
  var graphic = new mars3d.graphic.BillboardEntity({
    name: poiName,
    position: [pos[0], pos[1], 10],
    style: {
      image: "img/marker/mark2.png",
      // scale: 10,
      scaleByDistance: true,
      scaleByDistance_far: 20000,
      scaleByDistance_farValue: 0.5,
      scaleByDistance_near: 1000,
      scaleByDistance_nearValue: 1,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      clampToGround: true,
      label: {
        text: poiText,
        font_size: 16,
        font_family: "微软雅黑",
        color: "#ffffff",
        pixelOffsetY: 20,
        distanceDisplayCondition: true,
        distanceDisplayCondition_far: 10000,
        distanceDisplayCondition_near: 0,
      },
    },

    // attr: { code:  },
  });

  // graphicLayer.on(mars3d.EventType.click, function (event) {
  //   console.log("监听layer，单击了矢量对象", event);
  // });

  var innerHtml = `<table style="width:280px;">
  <tr><th scope="col" colspan="4"  style="text-align:center;font-size:15px;">graphic.bindPopup局部刷新</th></tr>
  <tr><td >说明：</td><td >鼠标单击信息弹窗 </td></tr>
  <tr><td >方式：</td><td >可以绑定任意html </td></tr>
  <tr><td >时间：</td><td id="tdTime"></td></tr>
  <tr><td colspan="4" style="text-align:right;cursor: pointer;"><button id="btnDetails">更多</button></td></tr>
</table>`;

  graphic.on(mars3d.EventType.popupOpen, function (event) {
    var container = event.container; // popup对应的DOM
    var btnDetails = container.querySelector("#btnDetails");
    if (btnDetails) {
      btnDetails.addEventListener("click", (e) => {
        // showXQ()
        toastr.info(graphic.name);
      });
    }
  });

  // 刷新局部DOM,不影响popup面板的其他控件操作
  graphic.on(mars3d.EventType.postRender, function (event) {
    var container = event.container; // popup对应的DOM
    var tdTime = container.querySelector("#tdTime");
    if (tdTime) {
      var date = mars3d.Util.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss S");
      tdTime.innerHTML = date;
    }
  });

  // 绑定Popup
  graphic.bindPopup(innerHtml, { offsetY: -30 }).openPopup();

  graphicLayer.addGraphic(graphic);
}
// 确认token获取状态
// var checkTokenFlag = setInterval(function () {
//   if (tokenFlag) {
//     console.log(tokenVal);
//     clearInterval(checkTokenFlag);
//   } else {
//     console.log("确认token获取状态...");
//     setInterval(checkTokenFlag);
//   }
// }, 1000);

// 画热力图
var heatLayer = null;
function drawHeat(arr) {
  if (heatLayer != null) {
    map.removeLayer(heatLayer);
    heatLayer == null;
  }
  heatLayer = new mars3d.layer.HeatLayer({
    positions: arr,
    // 以下为热力图本身的样式参数，可参阅api：https://www.patrick-wied.at/static/heatmapjs/docs.html
    heatStyle: {
      radius: 250,
      blur: 1,
    },
    // 以下为矩形矢量对象的样式参数
    style: {
      opacity: 0.6,
      clampToGround: true,
      // classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
      arc: true, // 是否为曲面
      // height: 0.0,
    },
  });
  map.addLayer(heatLayer);
  console.log("load-heatLayer");

  // map.on(mars3d.EventType.mouseMove, (e) => {
  //   var point = mars3d.LatLngPoint.fromCartesian(e.cartesian);
  //   console.log(point);
  //   // var data = heatLayer.getPointData(point);

  //   // var inhtml = `
  //   //   经度: ${point.lng} <br />
  //   //   纬度: ${point.lat} <br />
  //   //   X值: ${data.x} <br />
  //   //   Y值: ${data.y} <br />
  //   //   value值: ${data.value} <br />
  //   //   颜色:<span style="background-color: ${data.color};padding:2px 5px;">${data.color}</span>
  //   //   `;
  //   // map.openSmallTooltip(e.windowPosition, inhtml);
  // });
}

// 获取热力图数据
heatPoiData = [];
function getheatData() {
  $.ajax({
    type: "POST",
    url: apiUrl + "comleader/dataOutput/getMapInfo",
    dataType: "application/json",
    headers: {
      "Content-Type": "application/json",
      accessToken: "comleader@123",
    },
    complete: (res) => {
      if (res.readyState == 4) {
        var resData = JSON.parse(res.responseText).data;
        heatPoiData = resData.pointList;
        console.log(heatPoiData);
        // 构建噪声热力图点位数据数组
        for (let i = 0; i < heatPoiData.length; i++) {
          // 删除空数据
          // if (heatPoiData[i].dataList.length != 0) {
          $("#roadOption").append(
            "<option value='" +
              i +
              "'>" +
              heatPoiData[i].pointName +
              "</option>"
          );
          // }
        }
      }
    },
  });
}

// 根据传入的经纬度点获取 长宽1000米的矩形geojson数据
var zoneBBox = {};
function getRectLatLngHandler(latlng, count, voiceVal) {
  const rectWidth = 1000 / 2; // 矩形宽度米
  const rectHeight = 1000 / 2; // 矩形高度米
  const center = latlng;
  const maxRadius = rectWidth;
  const minRadius = rectHeight;
  const options = {
    steps: 4,
    units: "meters",
  };

  const maxCircle = turf.circle(center, maxRadius, options);
  const minCircle = turf.circle(center, minRadius, options);
  const leftLon = maxCircle.geometry.coordinates[0][1][0];
  const rightLon = maxCircle.geometry.coordinates[0][3][0];
  const topLat = minCircle.geometry.coordinates[0][0][1];
  const bottomLat = minCircle.geometry.coordinates[0][2][1];
  // console.log(leftLon, rightLon);
  // console.log(topLat, bottomLat);
  zoneBBox = {
    xmin: leftLon,
    xmax: rightLon,
    ymin: bottomLat,
    ymax: topLat,
  };
  console.log(zoneBBox);
  // 如果点位DataList为空，则提示用户
  if (count == 0) {
    toastr.error("此点位无数据！");
  } else {
    getheatPoint(count, voiceVal);
  }
  // return zoneBBox;
}
// 构建噪声热力区域点
// 目前噪声点为在给定的点位生成的矩形中随机取点
function getheatPoint(count, voiceVal) {
  var arr = [];
  var arrPoint = turf.randomPoint(count, {
    bbox: [zoneBBox.xmin, zoneBBox.ymin, zoneBBox.xmax, zoneBBox.ymax],
  }).features; // 随机点
  for (var i = 0; i < arrPoint.length; i++) {
    var item = arrPoint[i].geometry.coordinates;
    // voiceVal为dataList中的噪声值
    arr.push({ lng: item[0], lat: item[1], value: voiceVal[i] });
  }
  console.log(arr);
  drawHeat(arr);
  // 飞行到热力图区域
  map.flyToExtent(zoneBBox, { scale: 5 });
  return arr;
}

getheatData();

// 监听下拉框变化
var selectPara;

// 街道
$("body").on("change", "select[name=streetOption]", function () {
  selectPara = $("#streetOption").find("option:selected").val();
  console.log(selectPara);
  loadListData(selectPara);
});
// 道路
$("body").on("change", "select[name=roadOption]", function () {
  selectPara = $("#roadOption").find("option:selected").val();
  console.log(selectPara);
  getRectLatLngHandler(
    [heatPoiData[selectPara].longitude, heatPoiData[selectPara].latitude],
    heatPoiData[selectPara].dataList.length,
    heatPoiData[selectPara].dataList
  );
});
// // OD
// $("body").on("change", "select[name=odOption]", function () {
//   selectPara = $("#odOption").find("option:selected").val();
//   if (!!selectPara) {
//     getResource(getResourceID(selectPara), tokenVal);
//   }
// });

// // 处理街道接口数据
// function fomartStreetData(_data) {
//   var newStreetData = [];
//   // for (let para of _data.value) {
//   //   console.log(para);
//   // }
//   //  _data.forEach(({}))
//   console.log(newStreetData);
// }
// // 街道数据三维画法
// var streetLayer;
// var pdStreetIndexInterval = [20000, 40000, 60000, 100000, 200000]; //预测年人口分布指数阈值
// var tdStreetIndexInterval = [0, 0.1, 0.5, 1, 2]; //预测面积阈值
// function drawStreetData(interval) {
//   if (streetLayer) {
//     map.removeLayer(streetLayer, true);
//   }
//   // 加载街道区划矢量数据
//   streetLayer = new mars3d.layer.GeoJsonLayer({
//     url: "https://wckj2020.obs.cn-south-1.myhuaweicloud.com:443/wckj/screen5-1/example/res/data/bjzone.json",
//     // url: "../example/res/data/newStreet.json",
//     mask: false, //标识为遮罩层【重点参数】
//     name: "街道数据",
//     symbol: {
//       type: "polygon",
//       styleOptions: {
//         fill: true,
//         // color: "rgb(2,26,79)",
//         opacity: 0.7,
//         outline: true,
//         outlineColor: "#F8F8FF",
//         outlineWidth: 2,
//         outlineOpacity: 0.8,
//         clampToGround: true,

//         label: {
//           //面中心点，显示文字的配置
//           text: "{SNAME}", //对应的属性名称
//           opacity: 1,
//           font_size: 16,
//           color: "#ffffff",
//           visibleDepth: false,

//           font_family: "微软雅黑",
//           outline: true,
//           outlineColor: "#00000",
//           outlineWidth: 5,

//           background: false,
//           backgroundColor: "#000000",
//           backgroundOpacity: 0.1,

//           font_weight: "bolder",
//           font_style: "normal",

//           // hasPixelOffset: true,
//           // pixelOffsetY: -30,

//           scaleByDistance: true,
//           scaleByDistance_far: 20000000,
//           scaleByDistance_farValue: 0.1,
//           scaleByDistance_near: 1000,
//           scaleByDistance_nearValue: 1,

//           distanceDisplayCondition: true,
//           distanceDisplayCondition_far: 20000,
//           distanceDisplayCondition_near: 0,
//         },
//       },
//       callback: function (attr, styleOpt) {
//         // console.log(reFormatStreetData[attr.STID]);
//         if (reFormatStreetData[attr.STID] <= interval[0]) {
//           styleOpt.color = "rgb(38,192,34)";
//         } else if (
//           interval[0] < reFormatStreetData[attr.STID] &&
//           reFormatStreetData[attr.STID] <= interval[1]
//         ) {
//           styleOpt.color = "rgb(154,252,43)";
//         } else if (
//           interval[1] < reFormatStreetData[attr.STID] &&
//           reFormatStreetData[attr.STID] <= interval[2]
//         ) {
//           styleOpt.color = "rgb(252,255,44)";
//         } else if (
//           interval[2] < reFormatStreetData[attr.STID] &&
//           reFormatStreetData[attr.STID] <= interval[3]
//         ) {
//           styleOpt.color = "rgb(250,209,39)";
//         } else if (
//           interval[3] < reFormatStreetData[attr.STID] &&
//           reFormatStreetData[attr.STID] <= interval[4]
//         ) {
//           styleOpt.color = "rgb(245,149,29)";
//         } else {
//           styleOpt.color = "rgb(232,4,29)";
//         }
//         return {
//           label: {
//             ...styleOpt.label,
//             text:
//               (attr.SNAME.indexOf("办") == -1
//                 ? attr.SNAME
//                 : attr.SNAME.substring(0, attr.SNAME.indexOf("办"))) +
//               ":\n" +
//               reFormatStreetData[attr.STID],
//           },
//         };
//       },
//     },
//   });

//   map.addLayer(streetLayer);
// }
